
#include "FindPasswordWebReq.h"

#include <core/QbLogger.h>
#include <core/thirdparty/json/reader.h>

#include <QByteArray>
#include <QtNetwork>

#include "FindPasswordDlg.h"
CFindPasswordMsg::CFindPasswordMsg() { Clear(); }

const CFindPasswordMsg& CFindPasswordMsg::operator=(
    const CFindPasswordMsg& obj) {
  m_nReqID = obj.m_nReqID;
  m_nResponse = obj.m_nResponse;
  m_strAccount = obj.m_strAccount;
  m_strUserID = obj.m_strUserID;
  m_strPassWord = obj.m_strPassWord;
  m_strMobile = obj.m_strMobile;
  m_strInititute = obj.m_strInititute;
  m_strDepartment = obj.m_strDepartment;
  m_strPosition = obj.m_strPosition;
  m_strTel = obj.m_strTel;
  m_strQQ = obj.m_strQQ;
  m_strBussiness = obj.m_strBussiness;
  m_strVerification = obj.m_strVerification;
  m_nMobileState = obj.m_nMobileState;
  m_bVerification = obj.m_bVerification;
  m_strSeverAdress = obj.m_strSeverAdress;
  return *this;
}

CFindPasswordMsg::CFindPasswordMsg(const CFindPasswordMsg& obj) { *this = obj; }

void CFindPasswordMsg::Clear() {
  m_nReqID = 0;
  m_nResponse = -1;
  m_strAccount = m_strUserID = m_strPassWord = m_strMobile = m_strInititute =
      m_strDepartment = "";
  m_strPosition = m_strTel = m_strQQ = m_strBussiness = m_strVerification = "";
  m_nMobileState = -1;
  m_bVerification = false;
  m_strSeverAdress = "";
}

CFindPasswordWebReq::CFindPasswordWebReq() {}

CFindPasswordWebReq::~CFindPasswordWebReq() { delete pMsg; }

void CFindPasswordWebReq::postMessageFunc(const CFindPasswordMsg& msg) {
  pMsg = new CFindPasswordMsg(msg);
  if (!pMsg) {
    log_info("find password thread msg is null !");
  }
  QString strJson = "";
  int nResult = -1;
  if (CFindPasswordWebReq::MakeJson(*pMsg, strJson)) {
    if (pMsg->m_nReqID == WEB_GET_SUBMIT_INFO) {  // post
      reqSumbmitInfo(*pMsg, strJson);
    } else if (pMsg->m_nReqID == WEB_GET_SET_PASSWORD) {  // put
      if (!pMsg->m_strPassWord.isEmpty()) {
        reqSubmitChangePwd(*pMsg, strJson);
        log_info("find password web req setp : %d",
                 pMsg->m_strPassWord.length());
      }
    } else {
      const QUrl url = QUrl::fromUserInput(strJson);
      if (url.isValid())
        m_reply = m_qNetAccessManager.get(QNetworkRequest(url));
      log_info("find password web req :%d  jsn: %s", pMsg->m_nReqID,
               strJson.toStdString().c_str());
    }
    connect(m_reply, &QNetworkReply::finished, this,
            &CFindPasswordWebReq::onGetResponse);
  } else {
    log_info("find password Make null !");
  }
}

void CFindPasswordWebReq::reqSumbmitInfo(CFindPasswordMsg& msg,
                                         QString strJson) {
  QNetworkRequest request;
  QString strPost = "";
  strPost += QString("?companyName=");
  strPost.append(msg.m_strInititute.toUtf8());
  strPost += QString("&dept=");
  strPost.append(msg.m_strDepartment.toUtf8());
  strPost += QString("&title=");
  strPost.append(msg.m_strPosition.toUtf8());
  if (!msg.m_strTel.isEmpty()) {
    strPost += QString("&mobile=");
    strPost.append(msg.m_strPosition.toUtf8());
  }
  if (!msg.m_strQQ.isEmpty()) {
    strPost += QString("&qq=");
    strPost.append(msg.m_strQQ.toUtf8());
  }
  if (!msg.m_strBussiness.isEmpty()) {
    strPost += QString("&businessType=");
    strPost.append(msg.m_strBussiness.toUtf8());
  }
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  request.setUrl(QUrl::fromUserInput(strJson));
  m_postReply = m_qNetAccessManager.post(request, strPost.toUtf8());
  connect(m_postReply, &QNetworkReply::finished, this,
          &CFindPasswordWebReq::onPostResponse);
}

void CFindPasswordWebReq::reqSubmitChangePwd(CFindPasswordMsg& msg,
                                             QString strJson) {
  QNetworkRequest request;
  QString strPost;
  strPost = "?password=";
  strPost.append(pMsg->m_strPassWord);

  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
  request.setUrl(QUrl::fromUserInput(strJson));

  m_putReply = m_qNetAccessManager.put(request, strPost.toUtf8());
  connect(m_putReply, &QNetworkReply::finished, this,
          &CFindPasswordWebReq::onPutResponse);
}

int CFindPasswordWebReq::DecodeJson(CFindPasswordMsg& msg,
                                    const QString& strJson) {
  if (strJson.isEmpty()) return -1;
  Json::Reader reader;
  Json::Value jvParent;
  std::string sRespon = strJson.toStdString();
  reader.parse(sRespon, jvParent);
  if (jvParent.size() <= 0) return -1;
  switch (msg.m_nReqID) {
    case WEB_GET_VERIFICATION_CODE:     // 1   //获取验证码
    case WEB_GET_VERIFICATION_CONFIRM:  //   2   //验证验证码
    case WEB_GET_SUBMIT_INFO:           //	 5 //提交信息
    case WEB_GET_SET_PASSWORD:          //	4 //设置密码
    {
      Json::Value jMenu = jvParent["meta"];
      if (!jMenu.isNull()) {
        if (jMenu["errNum"].isNull() || !jMenu["errNum"].isInt()) {
          log_error("decode req:%d num is error", msg.m_nReqID);
          return -1;
        }
        int nError = jMenu["errNum"].asInt();
        if (msg.m_nReqID == WEB_GET_VERIFICATION_CONFIRM ||
            msg.m_nReqID == WEB_GET_VERIFICATION_CODE) {
          Json::Value jData = jvParent["data"];
          if (!jData.isNull() && jData.isBool()) {
            if (jData.asBool())
              return 1;
            else
              return -1;
          }
        } else {
          return nError;
        }
      }
      return -1;
    }
    case WEB_GET_VERIFICATION_MOBILE_STATE:  // 获取手机状态
    {
      Json::Value jMenu = jvParent["data"];
      if (!jMenu.isNull()) {
        Json::Value jMobileStatus = jMenu["mobileStatus"];
        Json::Value jUserID = jMenu["userId"];
        Json::Value jUserName = jMenu["username"];
        if (!jUserID.isNull() && jUserID.isString()) {
          //	msg.m_strUserID.arg("%s", jID.asCString());
          msg.m_strUserID = jUserID.asCString();
        }
        if (!jUserName.isNull() &&
            jUserName
                .isString()) /*msg.m_strAccount.arg("%s",jAct.asCString());*/
          msg.m_strAccount = jUserName.asCString();
        int nError = -1;
        if (!jMobileStatus.isNull() && jMobileStatus.isInt())
          nError = jMobileStatus.asInt();
        msg.m_nMobileState = nError;
        return nError;
      }
      return -1;
    }
    default:
      return -1;
  }
  return -1;
}

bool CFindPasswordWebReq::MakeJson(const CFindPasswordMsg& msg,
                                   QString& strJson) {
  if (msg.m_strSeverAdress.isEmpty()) {
    log_info("find password web req sever is null");
    return false;
  }

  switch (msg.m_nReqID) {
    case WEB_GET_VERIFICATION_CODE:  // 1   //获取验证码
    {
      if (msg.m_strMobile.isEmpty()) {
        log_info("find password web req sever 1 id or mob is null");
        return false;
      }
      strJson = QString("%1/edm/api/v1/mobile/code?mobile=%2")
                    .arg(msg.m_strSeverAdress)
                    .arg(msg.m_strMobile);
      return true;
    }
    case WEB_GET_VERIFICATION_CONFIRM:  //   2   //验证验证码
    {
      if (msg.m_strMobile.isEmpty() || msg.m_strVerification.isEmpty()) {
        log_info("find password web req sever 2 ver id or mob is null");
        return false;
      }
      strJson = QString("%1/edm/api/v1/mobile/code/verify?mobile=%2&code=%3")
                    .arg(msg.m_strSeverAdress)
                    .arg(msg.m_strMobile)
                    .arg(msg.m_strVerification);
      return true;
    }
    case WEB_GET_VERIFICATION_MOBILE_STATE:  //      3 //获取手机状态
    {
      if (msg.m_strMobile.isEmpty()) {
        log_info("find password web req sever 3 ver id or mob is null");
        return false;
      }
      strJson = QString("%1/edm/api/v1/qb/verification/mobile/state?mobile=%2")
                    .arg(msg.m_strSeverAdress)
                    .arg(msg.m_strMobile);
      return true;
    }
    case WEB_GET_SET_PASSWORD:  //	4 //设置密码
    {
      if (msg.m_strUserID.isEmpty() || msg.m_strPassWord.isEmpty()) {
        log_info("find password web req sever 4 ver id or mob is null");
        return false;
      }
      strJson = QString("%1/edm/api/v1/users/%2/password")
                    .arg(msg.m_strSeverAdress)
                    .arg(msg.m_strUserID);
      return true;
      break;
    }
    case WEB_GET_SUBMIT_INFO:  //	 5 //提交信息
    {
      strJson = QString("%1/edm/api/v1/qb/verification/users/%2")
                    .arg(msg.m_strSeverAdress)
                    .arg(msg.m_strUserID);
      return true;
      // POST /edm/api/v1/qb/verification/users/{userId}
      // userId			用户信息
      // companyName			机构名
      // dept			用户信息
      // title			用户信息
      // mobile		用户信息
      // qq			用户信息
      // businessType			用户信息
    }
    default:
      return false;
  }
  return false;
}

void CFindPasswordWebReq::onGetResponse() {
  QByteArray bytes = m_reply->readAll();
  m_strRespon = QString::fromStdString(bytes.toStdString());
  int nResult = CFindPasswordWebReq::DecodeJson(*pMsg, m_strRespon);
  if (nResult < 0) nResult = -1;
  pMsg->m_nResponse = nResult;
  emit SendGetMsgComplete();
}

void CFindPasswordWebReq::onPostResponse() {
  QByteArray bytes = m_postReply->readAll();
  m_strRespon = QString::fromStdString(bytes.toStdString());
  int nResult = CFindPasswordWebReq::DecodeJson(*pMsg, m_strRespon);
  if (nResult < 0) nResult = -1;
  pMsg->m_nResponse = nResult;
  emit SendPostMsgComplete();
}

void CFindPasswordWebReq::onPutResponse() {
  QByteArray bytes = m_putReply->readAll();
  m_strRespon = QString::fromStdString(bytes.toStdString());
  int nResult = CFindPasswordWebReq::DecodeJson(*pMsg, m_strRespon);
  if (nResult < 0) nResult = -1;
  pMsg->m_nResponse = nResult;
  emit SendPutMsgComplete();
}
